<?php

class User extends Cartalyst\Sentry\Users\Eloquent\User implements Robbo\Presenter\PresentableInterface {

    /**
     * Constructor
     */
    public function __construct (array $attributes = array()) {}
    
    public function getPresenter () {}
    
    
    /**
     * get all user where delete = false
     * @author Thuan Truong
     */
    public function getAllUser () {
        $users = User::where('is_deleted', '=', 0)->get();
        return $users;
    }
    
    /**
     * count all user where delete = false
     * @author Thuan Truong
     */
    public function countAllUser () {
        $users = User::where('is_deleted', '=', 0)->count();
        return $users;
    }
    
    /**
     * find user by id
     * @author Thuan Truong
     */
    public function findUserByID ($id) {
        $user = DB::table('users')->where('id', $id)->first();
        
        if (empty($user)) {
            App::abort(404);
        }
        return $user; 
    }
    
    /**
     * delete user
     * @author Thuan Truong
     */
    public function deleteUser($id) {
        DB::table('users')
            ->where('id', $id)
            ->update(array('is_deleted' => 1));
    }
    
    
    /**
     * check login with admin
     * @author Thuan Truong
     */
    public function adminLogin ($input) {
        
    }
    
    /**
      * validate for login
      * @author Thuan Truong
      * @param input
      * @return array
      */
     public function validateLogin($input) {
        $rules = array(
            'email' => 'required|min:4|max:100|email',
            'password' => 'required|min:5|max:50',
        );
            
        $validator = Validator::make($input, $rules);
        return $validator;
     }
     
     
     /**
     * Check login user
     * @author Thuan Truong
     * @param email, password or activation_code
     * @return integer ( 0->false, 1->user login with email)
     */
     public function userLogin($username, $password)
     {        
         $userEmail = $this->findUserbyEmail($username);
         
         if (!empty($userEmail)) {  //login with email 
            $user = User::find($userEmail[0]->id);
            if (Hash::check($password, $user->password)) return 1;
            return 0;
         } else{ 
             return 0;
         }
     }
	 
        
     /**
      * find User by email
      * @author Thuan Truong
      * @param email
      * @return array
      */
     public function findUserbyEmail($email) {
         $users = DB::table('users')->where('is_deleted', '=', 0)
             ->where('email', '=', $email)
             ->get();
         return $users;
     }
     
	 
	 /**
      * validate for register
      * @author Thuan Truong
      * @param input
      * @return array
      */
     public function validateRegister($input) {
        $rules = array(
            'full_name' => 'required|min:3|max:250',
            'email' => 'required|email|unique:users,email,NULL,id,is_deleted,0|max:100',
            'phone' => 'required|min:8|max:15',
            'address' => 'min:4|max:500',
        );
            
        $validator = Validator::make($input, $rules);
        return $validator;
     }
     
     /**
      * validate for update
      * @author Thuan Truong
      * @param input
      * @return array
      */
     public function validateUpdate($input) {
        $rules = array(
            'full_name' => 'required|min:3|max:250',
            'email' => 'required|email|max:100',
            'phone' => 'required|min:8|max:15',
            'address' => 'min:4|max:500',
        );
            
        $validator = Validator::make($input, $rules);
        return $validator;
     }
     
     
     /**
      * save user 
      * @author Thuan Truong
      */
     public function registerUser ($input) {
         
        $user = new User();
        $user->setHasher(new Cartalyst\Sentry\Hashing\NativeHasher);            
        $user -> full_name = $input['full_name'];           
        $user -> email = $input['email'];
        $user -> password = 123456;
        $user -> phone = $input['phone'];
        $user -> address = $input['address'];
		$user -> dob = strtotime(date('Y-m-d H:i', strtotime(str_replace('/', '-', $input['dob']))));
		$user -> gender = $input['gender'];
        $user -> activated = 1;
        $user -> activation_code = Hash::make('123456');
        $user -> save();
        
        $group = Sentry::findGroupById($input['role']);
        $user->addGroup($group);        
     }

	 /**
      * update user 
      * @author Thuan Truong
      */
     public function updateUser ($input, $id) {
         
        $user = User::find($id);
        $user -> full_name = $input['full_name'];           
        $user -> email = $input['email'];
        $user -> phone = $input['phone'];
        $user -> address = $input['address'];
		$user -> dob = strtotime(date('Y-m-d H:i', strtotime(str_replace('/', '-', $input['dob']))));
        $user -> update();
        
     }
	 
	 
	 /**
     * Get user group id
     * @author Trung Vuong
     * @return int or null
     */
    public function getGroupId()
    {
        $groups = $this->getGroups();

        if ($groups->isEmpty()) {
            return null;
        }
        return $groups[0]->getId();
    }

    /**
     * Check if a user is not inferior to another in terms of role (group)
     * @author Trung Vuong
     * @param int or User $user
     * @return boolean
     */
    public function isNotInferiorTo($user)
    {
        if (! is_object($user)) {
            $user = Sentry::findUserById($user);
        }
        
        if ($this->getGroupId() <= $user->getGroupId()) {
            return true;
        }
        return false;
    }

    /**
     * Check if a user can edit another
     * @author Trung Vuong
     * @param int or User $user
     * @return boolean
     */
    public function canEditUser($user)
    {
        return $this->hasAccess('user.edit') && $this->isNotInferiorTo($user);
    }

    /**
     * Check if a user can delete another
     * @author Trung Vuong
     * @param int or User $user
     * @return boolean
     */
    public function canDeleteUser($user)
    {
        $userId = is_object($user) ? $user->getId() : $user;
        return $this->hasAccess('user.delete') && $this->isNotInferiorTo($user) && $this->getId() !== $userId;
    }
    
  
    /**
     * get role for user
     * @author Thuan Truong
     * @param id
     * @return int
     */
    public function getRole($user) {
        $users = Sentry::findUserById($user);
        $groups = $users->getGroups();
        return $groups[0]->id;   
    }
    
    /**
     * get Group Name by id user
     * @author Thuan Truong
     * @return string
     */
    public function getGroupNamebyID($id) {
        $user = Sentry::findUserByID($id);
        $groups = $user->getGroups();
        return $groups[0]->getName();
    }


    /**
     * Replace user group given group id
     * @author Trung Vuong
     * @param int $groupId
     */
    private function replaceGroupById($groupId)
    {
        $group = Sentry::findGroupById($groupId);
        if ( ! $this->inGroup($group) ) {
            $cur_groups = $this->getGroups();
            foreach ($cur_groups as $cur_group) {
                $this->removeGroup($cur_group);
            }
            $this->addGroup($group);
        }
    }
	 
     
     /**
      * Get all admins
      * @author Duc Nguyen
      */
     public function getAdmins() {
        $adminGroup = Sentry::findGroupByName('admin');
        $admins = Sentry::findAllUsersInGroup($adminGroup);
        return $admins;
     }
     
     /**
      * Get all managers
      * @author Duc Nguyen
      */
     public function getManagers() {
        $managerGroup = Sentry::findGroupByName('manager');
        $managers = Sentry::findAllUsersInGroup($managerGroup);
        return $managers;
     }

     
     /**
      * Get all users
      * @author Duc Nguyen
      */
     public function getUsers() {
        $userGroup = Sentry::findGroupByName('user');
        $users = Sentry::findAllUsersInGroup($userGroup);
        return $users;
     }
}